package com.nervenets.general.utils;

import com.nervenets.general.Global;

import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.commons.lang3.StringUtils.trim;

/**
 * Created by Joe
 * Date: 2011-5-2 22:04:45
 */
public final class StringUtils {
    public static String toUTF8(String value) {
        byte[] bytes = value.getBytes(StandardCharsets.ISO_8859_1);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String chinaToUnicode(String str) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {//汉字范围 \u4e00-\u9fa5 (中文)
                result.append("\\u").append(Integer.toHexString(chr1));
            } else {
                result.append(str.charAt(i));
            }
        }
        return result.toString();
    }

    public static String filterEmoji(String source) {
        if (null == source) return null;
        if (!isBlank(source)) {
            return source.replaceAll("[^\\u0000-\\uFFFF]", "").trim();
        } else {
            return source.trim();
        }
    }

    public static boolean hasAnyEmpty(String... strings) {
        for (String string : strings) {
            if (org.springframework.util.StringUtils.isEmpty(string)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isEmail(String email) {
        Pattern pattern = Pattern.compile("\\w+@(\\w+\\.){1,3}\\w+");
        Matcher matcher = pattern.matcher(email);
        return matcher.find();
    }

    public static boolean isMobile(String email) {
        Pattern pattern = Pattern.compile(Global.RegExp.MOBILE);
        Matcher matcher = pattern.matcher(email);
        return matcher.find();
    }

    public static boolean isRedisNull(String string) {
        return org.springframework.util.StringUtils.isEmpty(string)
                || "NIL".equalsIgnoreCase(string)
                || "NULL".equalsIgnoreCase(string);
    }

    public static boolean isEmpty(String string) {
        return org.springframework.util.StringUtils.isEmpty(string);
    }

    public static String toString(Object obj) {
        return null == obj ? "" : String.valueOf(obj);
    }

    public static String randomString(int length) {
        String chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
        //默认去掉了容易混淆的字符oO,Ll,9gq,Vv,Uu,I1
        int maxPos = chars.length();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {
            result.append(chars.charAt(NumberUtil.randomNumber(0, maxPos - 1)));
        }
        return result.toString();
    }

    public static String zeroBeginFillString(int number, int length) {
        final String numberStr = number + "";
        if (numberStr.length() >= length) return numberStr;
        StringBuilder result = new StringBuilder();
        for (int i = numberStr.length(); i < length; i++) {
            result.append("0");
        }
        result.append(numberStr);
        return result.toString();
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((!Character.isWhitespace(str.charAt(i)))) {
                return false;
            }
        }
        return true;
    }

    public static String clearHtmlTags(String string) {
        String regEx_html = "<[^>]+>";

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(string);
        string = m_html.replaceAll(""); //过滤html标签

        return trim(string); //返回文本字符串
    }

    public static String formatKey(Object... objects) {
        return org.apache.commons.lang3.StringUtils.joinWith("~", objects);
    }

    public static boolean isIDNumber(String IDNumber) {
        if (IDNumber == null || "".equals(IDNumber)) {
            return false;
        }
        // 定义判别用户身份证号的正则表达式（15位或者18位，最后一位可以为字母）
        String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
                "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
        //假设18位身份证号码:41000119910101123X  410001 19910101 123X
        //^开头
        //[1-9] 第一位1-9中的一个      4
        //\\d{5} 五位数字           10001（前六位省市县地区）
        //(18|19|20)                19（现阶段可能取值范围18xx-20xx年）
        //\\d{2}                    91（年份）
        //((0[1-9])|(10|11|12))     01（月份）
        //(([0-2][1-9])|10|20|30|31)01（日期）
        //\\d{3} 三位数字            123（第十七位奇数代表男，偶数代表女）
        //[0-9Xx] 0123456789Xx其中的一个 X（第十八位为校验值）
        //$结尾

        //假设15位身份证号码:410001910101123  410001 910101 123
        //^开头
        //[1-9] 第一位1-9中的一个      4
        //\\d{5} 五位数字           10001（前六位省市县地区）
        //\\d{2}                    91（年份）
        //((0[1-9])|(10|11|12))     01（月份）
        //(([0-2][1-9])|10|20|30|31)01（日期）
        //\\d{3} 三位数字            123（第十五位奇数代表男，偶数代表女），15位身份证不含X
        //$结尾


        boolean matches = IDNumber.matches(regularExpression);

        //判断第18位校验值
        if (matches) {
            if (IDNumber.length() == 18) {
                try {
                    char[] charArray = IDNumber.toCharArray();
                    //前十七位加权因子
                    int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
                    //这是除以11后，可能产生的11位余数对应的验证码
                    String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
                    int sum = 0;
                    for (int i = 0; i < idCardWi.length; i++) {
                        int current = Integer.parseInt(String.valueOf(charArray[i]));
                        int count = current * idCardWi[i];
                        sum += count;
                    }
                    char idCardLast = charArray[17];
                    int idCardMod = sum % 11;
                    return idCardY[idCardMod].equalsIgnoreCase(String.valueOf(idCardLast));
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }

        }
        return matches;
    }

    public static String placeholder(boolean condition, String source, String placeholder) {
        return condition ? source : placeholder;
    }

    /**
     * 驼峰转分隔
     *
     * @param text
     * @return
     */
    public static String camelToCharacterSeparation(String text, String replace) {
        Matcher matcher = Pattern.compile("[A-Z0-9]").matcher(text);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, replace + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        final String result = sb.toString();
        return result.startsWith(replace) ? result.substring(replace.length()) : result;
    }

}
